from watchdog.observers import Observer
from watchdog.events import *
import logging
import time
import smtplib

# MIMEText是html格式的邮件用的
from email.mime.text import MIMEText


def sendAEmail(content):
    sender = '2234318868@qq.com'
    receiver = '2234318868@qq.com'
    msg = MIMEText(content)
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = '主题：SMTP测试'
    try:
        smtpobj = smtplib.SMTP('smtp.qq.com',25)
        # 25为smtp默认端口号
        # smtpobj.connect('mailteam@qq.com',25)
        smtpobj.login('2234318868','yjfjoblyxryyeabf')
        smtpobj.sendmail(sender,receiver,msg.as_string())
        print('发送成功')
    except smtplib.SMTPException as e:
        print('邮件发送失败，失败原因是：{}'.format(e))


class SEmail(FileSystemEventHandler):
    def on_modified(self,event):
        mail_msg = f"{event.src_path}被修改"
        sendAEmail(mail_msg)

    def on_created(self,event):
        mail_msg = f"{event.src_path}被创建"
        sendAEmail(mail_msg)

    def on_deleted(self,event):
        mail_msg = f"{event.src_path}被删除"
        sendAEmail(mail_msg)

    def on_moved(self,event):
        mail_msg = f"{event.src_path}被移动到{event.dest_path}"
        sendAEmail(mail_msg)


# 路径
path = "/etc"

# 日志基础设置,日志等级info，格式时间加信息
logging.basicConfig(level = logging.INFO,format='%(asctime)s %(message)s',datefmt='%Y-%m-%d %H:%M:%S')

# 事件处理器
log_event_handler = SEmail()

# 创建监控对象
obs = Observer()

# 指定监控对象，以及事件处理器
obs.schedule(log_event_handler,path,recursive=True)

# 启动线程
obs.start()

# 对KeyboardInterrupt异常进行处理
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    obs.stop()

# 等待所有线程结束，才结束主进程
obs.join()


